package com.ae.shield.common.capability.energy;

import com.ae.shield.common.items.util.ItemNBTHelper;
import net.minecraft.item.ItemStack;
import net.minecraftforge.energy.IEnergyStorage;

public class ItemEnergyStorage implements IEnergyStorage {
    private final String TAG_ENERGY = "fe_energy";
    protected final ItemStack stack;
    protected int capacity;
    protected int maxReceive;
    protected int maxExtract;

    public ItemEnergyStorage(ItemStack stack, int capacity, int maxExtract, int maxReceive){
        this.stack = stack;
        this.capacity = capacity;
        this.maxExtract = maxExtract;
        this.maxReceive = maxReceive;
    }

    @Override
    public int receiveEnergy(int maxReceive, boolean simulate) {
        if (!canReceive())
            return 0;

        int energyReceived = Math.min(capacity - getEnergyStored(), Math.min(this.maxReceive, maxReceive));
        if (!simulate)
            ItemNBTHelper.setInt(stack, TAG_ENERGY, getEnergyStored() + energyReceived);
        return energyReceived;
    }

    @Override
    public int extractEnergy(int maxExtract, boolean simulate) {
        if (!canExtract())
            return 0;

        int energyExtracted = Math.min(getEnergyStored(), Math.min(this.maxExtract, maxExtract));
        if (!simulate)
            ItemNBTHelper.setInt(stack, TAG_ENERGY, getEnergyStored() - energyExtracted);
        return energyExtracted;
    }

    @Override
    public int getEnergyStored() {
        return ItemNBTHelper.getInt(stack, TAG_ENERGY, 0);
    }

    @Override
    public int getMaxEnergyStored()
    {
        return capacity;
    }

    @Override
    public boolean canExtract()
    {
        return this.maxExtract > 0;
    }

    @Override
    public boolean canReceive()
    {
        return this.maxReceive > 0;
    }
}

